<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>市级政务云租用明细 - 在线评测系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        /* 主要内容样式 */
        .main-content {
            padding: 20px;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e8e8e8;
        }

        .page-title {
            font-size: 20px;
            font-weight: 500;
            color: #333;
        }

        .btn-group {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .btn-primary {
            background-color: #1890ff;
            color: #fff;
        }

        .btn-primary:hover {
            background-color: #40a9ff;
        }

        .btn-default {
            background-color: #f5f5f5;
            color: #333;
            border: 1px solid #d9d9d9;
        }

        .btn-default:hover {
            background-color: #e8e8e8;
        }

        /* 步骤导航 */
        .steps-container {
            display: flex;
            margin: 30px 0;
            position: relative;
        }

        .steps-container::before {
            content: '';
            position: absolute;
            top: 16px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #e8e8e8;
            z-index: 1;
        }

        .step {
            flex: 1;
            text-align: center;
            position: relative;
            z-index: 2;
        }

        .step-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #f5f5f5;
            border: 2px solid #e8e8e8;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 10px;
            font-weight: bold;
            color: #999;
        }

        .step.active .step-icon {
            background-color: #1890ff;
            border-color: #1890ff;
            color: #fff;
        }

        .step.completed .step-icon {
            background-color: #52c41a;
            border-color: #52c41a;
            color: #fff;
        }

        .step-title {
            font-size: 14px;
            color: #999;
            margin-top: 5px;
        }

        .step.active .step-title {
            color: #1890ff;
            font-weight: 500;
        }

        .step.completed .step-title {
            color: #52c41a;
        }

        /* 表单样式 */
        .form-container {
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 20px;
        }

        .form-header {
            padding-bottom: 15px;
            margin-bottom: 20px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .form-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
        }

        .form-actions {
            display: flex;
            justify-content: center;
            margin-top: 30px;
            gap: 15px;
        }

        .form-actions .btn {
            min-width: 100px;
        }

        /* 政务云租用明细表格样式 */
        .cloud-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        .cloud-table th, 
        .cloud-table td {
            border: 1px solid #e8e8e8;
            padding: 12px 15px;
            text-align: center;
        }
        
        .cloud-table th {
            background-color: #f5f7fa;
            font-weight: 500;
            color: #333;
            white-space: nowrap;
        }
        
        .amount-cell {
            text-align: right;
        }
        
        .cloud-input {
            width: 100%;
            padding: 5px 8px;
            border: none;
            border-radius: 0;
            background-color: transparent;
            outline: none;
        }
        
        .cloud-input:focus,
        .category-input:focus {
            box-shadow: none;
        }
        
        .cloud-input.text-right {
            text-align: right;
        }
        
        .add-row-btn {
            margin: 10px 0;
            background-color: #f5f5f5;
            border: 1px dashed #d9d9d9;
            padding: 8px 0;
            width: 100%;
            text-align: center;
            cursor: pointer;
            color: #1890ff;
        }
        
        .add-row-btn:hover {
            background-color: #e6f7ff;
        }
        
        .add-category-row {
            margin: 5px 0;
            background-color: #f5f5f5;
            border: 1px dashed #d9d9d9;
            padding: 8px 0;
            width: 100%;
            text-align: center;
            cursor: pointer;
            color: #1890ff;
            transition: all 0.3s;
            font-size: 14px;
        }
        
        .add-category-row:hover {
            background-color: #e6f7ff;
            border-color: #91caff;
        }
        
        .not-applicable-checkbox {
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #333;
        }
        
        .category-header {
            background-color: #e6f7ff;
            font-weight: bold;
        }
        
        .module-desc {
            text-align: left;
            padding: 15px;
            margin-top: 15px;
            background-color: #f9f9f9;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        /* 操作按钮样式 */
        .btn-add, .btn-delete {
            margin: 0 3px;
            border: 1px solid;
            background-color: white;
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.2s;
            display: inline-block;
            font-size: 12px;
        }
        
        .btn-add {
            color: #1890ff;
            border-color: #1890ff;
        }
        
        .btn-delete {
            color: #ff4d4f;
            border-color: #ff4d4f;
        }
        
        .btn-add:hover {
            color: white;
            background-color: #1890ff;
        }
        
        .btn-delete:hover {
            color: white;
            background-color: #ff4d4f;
        }
        
        .btn-add i, .btn-delete i {
            margin-right: 3px;
        }
        
        .operation-cell {
            white-space: nowrap;
            text-align: center;
        }
        
        /* 添加云资源按钮 */
        .btn-cloud-add {
            background-color: #1890ff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 15px auto;
            transition: all 0.3s;
        }
        
        .btn-cloud-add:hover {
            background-color: #40a9ff;
            box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
        }
        
        .btn-cloud-add i {
            margin-right: 5px;
        }
        
        /* 新增样式 */
        /* For the row containing the merged category cell */
        .service-category-row td {
            padding: 10px 15px;
            text-align: left; /* Default text alignment */
        }

        /* For the merged category name cell specifically */
        .service-category-row .category-name-cell {
            vertical-align: middle;
            text-align: center;
            background-color: #e6f7ff;
            font-weight: bold;
            color: #333;
        }
        
        .category-input {
            border: none;
            border-radius: 0;
            padding: 4px 8px;
            font-size: 16px;
            font-weight: bold;
            color: #333;
            background-color: transparent;
            width: auto;
            min-width: 120px;
            text-align: center;
            outline: none;
        }
        
        .category-actions {
            margin-top: 10px;
        }
        
        .service-row td {
            background-color: #ffffff;
            vertical-align: middle;
        }

        /* For the "Add Service Name" button row */
        .add-service-row-button-row td {
            background-color: #f9f9f9; /* Slightly different background for visual separation */
            text-align: center; /* Center the button */
            padding: 10px 0;
        }
        
        /* Common style for table action buttons (add service name) */
        .table-action-btn {
            background-color: #f5f5f5;
            border: 1px dashed #d9d9d9;
            padding: 8px 0;
            width: 90%;
            max-width: 250px;
            text-align: center;
            cursor: pointer;
            color: #1890ff;
            transition: all 0.3s;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }
        
        .table-action-btn:hover {
            background-color: #e6f7ff;
            border-color: #91caff;
        }

        /* 首先修改CSS样式，使删除按钮更简洁 */
        .btn-delete-service-row {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 20px;
            font-weight: bold;
            line-height: 1;
            padding: 0 6px;
            vertical-align: middle;
            color: #ff4d4f;
        }

        .btn-delete-service-row:hover {
            color: #666;
            background-color: transparent;
        }

        /* 修改CSS样式部分，增加样式类 */
        .btn-add-service, .btn-delete-service {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 20px;
            font-weight: bold;
            line-height: 1;
            padding: 0 6px;
            vertical-align: middle;
        }

        .btn-add-service {
            color: #1890ff;
        }

        .btn-delete-service {
            color: #ff4d4f;
        }

        .btn-add-service:hover, .btn-delete-service:hover {
            color: #666;
            background-color: transparent;
        }

        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none; /* 默认隐藏 */
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .modal-content {
            background-color: #fff;
            padding: 25px;
            border-radius: 8px;
            width: 90%;
            max-width: 1000px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        
        /* 修复预览表格表头样式 */
        #previewModal th {
            white-space: normal !important;
            height: 60px !important;
            vertical-align: middle !important;
            font-size: 14px !important;
            padding: 5px !important;
            line-height: 1.4 !important;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e8e8e8;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .modal-header h2 {
            font-size: 18px;
            font-weight: 500;
        }
        
        .modal-close-btn {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #888;
            line-height: 1;
        }
        
        .preview-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        
        .preview-table th, .preview-table td {
            border: 1px solid #e8e8e8;
            padding: 10px 12px;
            text-align: left;
        }
        
        .preview-table th {
            background-color: #f9f9f9;
            font-weight: 500;
            text-align: center;
            white-space: normal;
            height: 60px;
            vertical-align: middle;
            font-size: 14px;
            padding: 5px;
            line-height: 1.4;
        }
        
        .preview-table .amount-preview-cell {
            text-align: right;
        }

        /* 隐藏数字输入框的上下箭头 */
        input[type=number]::-webkit-inner-spin-button,
        input[type=number]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        input[type=number] {
            -moz-appearance: textfield;
        }
    </style>
</head>
<body>
    <div class="main-content">
        <!-- 步骤导航 -->
        <div class="steps-container">
            <div class="step completed">
                <div class="step-icon">1</div>
                <div class="step-title">基本信息</div>
            </div>
            <div class="step completed">
                <div class="step-icon">2</div>
                <div class="step-title">预算总表</div>
            </div>
            <div class="step completed">
                <div class="step-icon">3</div>
                <div class="step-title">产品购置明细</div>
            </div>
            <div class="step completed">
                <div class="step-icon">4</div>
                <div class="step-title">软件开发明细</div>
            </div>
            <div class="step completed">
                <div class="step-icon">5</div>
                <div class="step-title">实施服务明细</div>
            </div>
            <div class="step active">
                <div class="step-icon">6</div>
                <div class="step-title">市级政务云租用</div>
            </div>
        </div>

        <!-- 表单 -->
        <div class="form-container">
            <div class="form-header">
                <h2 class="form-title">市级政务云租用明细表</h2>
                <div class="btn-group">
                    <button class="btn btn-default" id="previewBtn">
                        <i class="fas fa-eye"></i> 预览
                    </button>
                    <button class="btn btn-default" id="exportBtn">
                        <i class="fas fa-file-export"></i> 导出
                    </button>
                </div>
            </div>

            <form id="cloudServiceForm">
                <div class="module-desc">
                    <p>本表填写市级政务云资源租用明细，包括各类虚拟机、存储、数据库等资源及其数量和费用。</p>
                </div>
                
                <!-- 政务云租用明细表格 -->
                <table class="cloud-table" id="cloudTable">
                    <thead>
                        <tr>
                            <th style="width: 8%;">服务类别</th>
                            <th style="width: 12%;">服务名称</th>
                            <th style="width: 18%;">项目</th>
                            <th style="width: 8%;">单位</th>
                            <th style="width: 10%;">单价</th>
                            <th style="width: 10%;">数量</th>
                            <th style="width: 10%;">租用期限</th>
                            <th style="width: 10%;">合计</th>
                            <th style="width: 10%;">备注</th>
                            <th style="width: 4%;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="cloudServiceBody">
                        <tr id="category-basic" class="service-category-row">
                            <td rowspan="6" class="category-name-cell">
                                <input type="text" class="category-input" value="基础服务" placeholder="服务类别名称">
                            </td>
                            <td><input type="text" class="cloud-input" name="service_name_1" value="计算服务"></td>
                            <td><input type="text" class="cloud-input" name="item_1" value="1CPU, 1GB内存"></td>
                            <td><input type="text" class="cloud-input" name="unit_1" value="元/月"></td>
                            <td><input type="number" class="cloud-input text-right" name="price_1" data-index="1"></td>
                            <td><input type="number" class="cloud-input" name="quantity_1" data-index="1"></td>
                            <td><input type="text" class="cloud-input" name="lease_term_1"></td>
                            <td><input type="text" class="cloud-input text-right" name="total_1" readonly></td>
                            <td><input type="text" class="cloud-input" name="notes_1"></td>
                            <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
                        </tr>
                        <tr class="service-row">
                            <td><input type="text" class="cloud-input" name="service_name_2" value="普通存储"></td>
                            <td><input type="text" class="cloud-input" name="item_2" value="1GB"></td>
                            <td><input type="text" class="cloud-input" name="unit_2" value="元/月"></td>
                            <td><input type="number" class="cloud-input text-right" name="price_2" data-index="2"></td>
                            <td><input type="number" class="cloud-input" name="quantity_2" data-index="2"></td>
                            <td><input type="text" class="cloud-input" name="lease_term_2"></td>
                            <td><input type="text" class="cloud-input text-right" name="total_2" readonly></td>
                            <td><input type="text" class="cloud-input" name="notes_2"></td>
                            <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
                        </tr>
                        <tr class="service-row">
                            <td><input type="text" class="cloud-input" name="service_name_3" value="高性能存储"></td>
                            <td><input type="text" class="cloud-input" name="item_3" value="1GB"></td>
                            <td><input type="text" class="cloud-input" name="unit_3" value="元/月"></td>
                            <td><input type="number" class="cloud-input text-right" name="price_3" data-index="3"></td>
                            <td><input type="number" class="cloud-input" name="quantity_3" data-index="3"></td>
                            <td><input type="text" class="cloud-input" name="lease_term_3"></td>
                            <td><input type="text" class="cloud-input text-right" name="total_3" readonly></td>
                            <td><input type="text" class="cloud-input" name="notes_3"></td>
                            <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
                        </tr>
                        <tr class="service-row">
                            <td><input type="text" class="cloud-input" name="service_name_4" value="互联网带宽"></td>
                            <td><input type="text" class="cloud-input" name="item_4" value="1Mbps"></td>
                            <td><input type="text" class="cloud-input" name="unit_4" value="元/月"></td>
                            <td><input type="number" class="cloud-input text-right" name="price_4" data-index="4"></td>
                            <td><input type="number" class="cloud-input" name="quantity_4" data-index="4"></td>
                            <td><input type="text" class="cloud-input" name="lease_term_4"></td>
                            <td><input type="text" class="cloud-input text-right" name="total_4" readonly></td>
                            <td><input type="text" class="cloud-input" name="notes_4"></td>
                            <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
                        </tr>
                        <tr class="service-row">
                            <td><input type="text" class="cloud-input" name="service_name_5" value="安全服务"></td>
                            <td><input type="text" class="cloud-input" name="item_5" value="1套"></td>
                            <td><input type="text" class="cloud-input" name="unit_5" value="元/月"></td>
                            <td><input type="number" class="cloud-input text-right" name="price_5" data-index="5"></td>
                            <td><input type="number" class="cloud-input" name="quantity_5" data-index="5"></td>
                            <td><input type="text" class="cloud-input" name="lease_term_5"></td>
                            <td><input type="text" class="cloud-input text-right" name="total_5" readonly></td>
                            <td><input type="text" class="cloud-input" name="notes_5"></td>
                            <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
                        </tr>
                        <tr>
                            <td colspan="9" style="text-align: center;">
                                <button type="button" class="btn-add-service" id="addServiceBtn">
                                    <i class="fas fa-plus-circle"></i> 添加服务名称
                                </button>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="7" style="text-align: right; background-color: #f0f5ff; font-weight: bold;">合计：</td>
                            <td style="background-color: #f0f5ff;"><input type="text" class="cloud-input text-right" id="overallTotal" readonly style="font-weight: bold; background-color: #f0f5ff; color: #1890ff;"></td>
                            <td colspan="2" style="background-color: #f0f5ff;"></td>
                        </tr>
                    </tfoot>
                </table>
                
                <button type="button" class="btn-cloud-add" id="addCategoryBtn">
                    <i class="fas fa-plus-circle"></i> 添加服务类别
                </button>
                
                <div class="module-desc">
                    <h4 style="margin-bottom: 10px;">政务云租用费用说明</h4>
                    <p>1. 费用计算采用年租用费用，总体项目费用中已包含项目周期内所有年度的云资源租用费用。</p>
                    <p>2. 虚拟机配置包括CPU核心数、内存大小、系统盘容量等信息。</p>
                    <p>3. 存储资源应注明类型（如块存储、对象存储等）及容量。</p>
                    <p>4. 数据库资源应注明数据库类型（如MySQL、Oracle等）、配置及版本。</p>
                </div>
                


                <div class="form-actions">
                    <button type="button" class="btn btn-default" id="prevBtn">
                        <i class="fas fa-arrow-left"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-default" id="saveBtn">
                        <i class="fas fa-save"></i> 保存
                    </button>
                    <button type="button" class="btn btn-primary" id="nextBtn" style="display: none;">
                        下一步 <i class="fas fa-arrow-right"></i>
                    </button>
                    <button type="button" class="btn btn-primary" id="submitBtn">
                        确认提交审核
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="previewModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h2>市级政务云租用明细表预览</h2>
                <button class="modal-close-btn">&times;</button>
            </div>
            <div class="modal-body">
                <!-- 预览表格将由JavaScript动态插入 -->
            </div>
        </div>
    </div>

    <script>
        // 自定义提示框
        function showCustomAlert(message) {
            // 检查是否已存在提示框
            let alertBox = document.getElementById('customAlertBox');
            
            if (!alertBox) {
                // 创建提示框
                alertBox = document.createElement('div');
                alertBox.id = 'customAlertBox';
                alertBox.style.position = 'fixed';
                alertBox.style.top = '50%';
                alertBox.style.left = '50%';
                alertBox.style.transform = 'translate(-50%, -50%)';
                alertBox.style.backgroundColor = 'white';
                alertBox.style.padding = '20px';
                alertBox.style.borderRadius = '8px';
                alertBox.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
                alertBox.style.zIndex = '2000';
                alertBox.style.minWidth = '300px';
                alertBox.style.textAlign = 'center';
                alertBox.style.animation = 'fadeIn 0.3s';
                
                // 添加动画样式
                const style = document.createElement('style');
                style.textContent = `
                    @keyframes fadeIn {
                        from { opacity: 0; transform: translate(-50%, -60%); }
                        to { opacity: 1; transform: translate(-50%, -50%); }
                    }
                `;
                document.head.appendChild(style);
                
                // 创建遮罩层
                const overlay = document.createElement('div');
                overlay.style.position = 'fixed';
                overlay.style.top = '0';
                overlay.style.left = '0';
                overlay.style.width = '100%';
                overlay.style.height = '100%';
                overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
                overlay.style.zIndex = '1999';
                document.body.appendChild(overlay);
                
                // 不添加标题，直接显示消息
                
                // 创建消息容器
                const messageDiv = document.createElement('div');
                messageDiv.textContent = message;
                messageDiv.style.margin = '15px 0';
                messageDiv.style.fontSize = '16px';
                messageDiv.style.color = '#333';
                alertBox.appendChild(messageDiv);
                
                // 创建确定按钮
                const confirmBtn = document.createElement('button');
                confirmBtn.textContent = '确定';
                confirmBtn.style.backgroundColor = '#4e7bef';
                confirmBtn.style.color = 'white';
                confirmBtn.style.border = 'none';
                confirmBtn.style.padding = '8px 40px';
                confirmBtn.style.borderRadius = '4px';
                confirmBtn.style.fontSize = '14px';
                confirmBtn.style.cursor = 'pointer';
                confirmBtn.style.transition = 'background-color 0.3s';
                
                confirmBtn.onmouseover = function() {
                    this.style.backgroundColor = '#3d6ae8';
                };
                
                confirmBtn.onmouseout = function() {
                    this.style.backgroundColor = '#4e7bef';
                };
                
                confirmBtn.onclick = function() {
                    document.body.removeChild(alertBox);
                    document.body.removeChild(overlay);
                };
                
                alertBox.appendChild(confirmBtn);
                document.body.appendChild(alertBox);
            } else {
                // 更新已存在提示框的消息
                alertBox.querySelector('div:nth-child(1)').textContent = message;
            }
        }
        
        // 验证数量是否为正整数
        function validateQuantity(input) {
            const value = input.value;
            // 检查是否为正整数
            if (value !== '' && (!/^\d+$/.test(value) || parseInt(value) <= 0)) {
                showCustomAlert('数量必须是正整数！');
                input.value = ''; // 清空无效输入
                return false;
            }
            return true;
        }
        
        // 计算金额
        function calculateAmount(index) {
            const priceInput = document.querySelector(`input[name="price_${index}"]`);
            const quantityInput = document.querySelector(`input[name="quantity_${index}"]`);
            const totalInput = document.querySelector(`input[name="total_${index}"]`);
            
            if (priceInput && quantityInput && totalInput) {
                // 验证数量是否为正整数
                if (!validateQuantity(quantityInput)) {
                    totalInput.value = "0.00";
                    calculateTotal();
                    return;
                }
                
                const price = parseFloat(priceInput.value) || 0;
                const quantity = parseInt(quantityInput.value) || 0;
                const amount = price * quantity;
                totalInput.value = amount.toFixed(2);
            }
            
            calculateTotal();
        }

        // 计算总计
        function calculateTotal() {
            let total = 0;
            const totalInputs = document.querySelectorAll('input[name^="total_"]');
            
            totalInputs.forEach(input => {
                total += parseFloat(input.value || 0);
                });
            
            document.getElementById('overallTotal').value = total.toFixed(2);
        }

        // 删除服务行
        // function deleteService(button) { // This function is now handled by the event listener
        //     const row = button.closest('tr');
        //     row.remove();
        //     calculateTotal();
        // }
        
        // 添加服务行
        function addService() {
            const serviceRows = document.querySelectorAll('#category-basic ~ .service-row');
            const newIndex = 'basic-' + (serviceRows.length + 1);
            
            // 创建新行
            const newRow = document.createElement('tr');
            newRow.className = 'service-row';
            
            // 设置新行内容
            newRow.innerHTML = `
                <td><input type="text" class="cloud-input" name="service_name_${newIndex}"></td>
                <td><input type="text" class="cloud-input" name="item_${newIndex}"></td>
                <td><input type="text" class="cloud-input" name="unit_${newIndex}" value="元/月"></td>
                <td><input type="number" class="cloud-input text-right" name="price_${newIndex}" data-index="${newIndex}"></td>
                <td><input type="number" class="cloud-input" name="quantity_${newIndex}" data-index="${newIndex}"></td>
                <td><input type="text" class="cloud-input" name="lease_term_${newIndex}"></td>
                <td><input type="text" class="cloud-input text-right" name="total_${newIndex}" readonly></td>
                <td><input type="text" class="cloud-input" name="notes_${newIndex}"></td>
                <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
            `;
            
            // 在添加按钮行前插入新行
            const addButtonRow = document.querySelector('#addServiceBtn').closest('tr');
            addButtonRow.parentNode.insertBefore(newRow, addButtonRow);
            
            // 为新行添加事件监听
            const priceInput = newRow.querySelector(`input[name="price_${newIndex}"]`);
            const quantityInput = newRow.querySelector(`input[name="quantity_${newIndex}"]`);
            
            if (priceInput) {
                priceInput.addEventListener('input', function() {
                    calculateAmount(newIndex);
                });
            }
            
            if (quantityInput) {
                quantityInput.addEventListener('input', function() {
                    calculateAmount(newIndex);
                });
            }

            // 更新rowspan
            updateCategoryRowspan('category-basic');
        }
        
        // 更新类别单元格的rowspan
        function updateCategoryRowspan(categoryId) {
            const categoryCell = document.querySelector(`#${categoryId} .category-name-cell`);
            if (categoryCell) {
                // 计算从类别行到下一个类别行（或表格末尾）之间的行数
                let rowCount = 1; // 从1开始，计算自身
                let currentRow = document.getElementById(categoryId).nextElementSibling;
                while(currentRow && !currentRow.classList.contains('service-category-row')) {
                    rowCount++;
                    currentRow = currentRow.nextElementSibling;
                }
                categoryCell.setAttribute('rowspan', rowCount); 
            }
        }
        
        // 修改初始化代码，整合事件处理
        document.addEventListener('DOMContentLoaded', function() {
            // 为价格和数量输入添加事件监听
            document.querySelectorAll('input[data-index]').forEach(input => {
                input.addEventListener('input', function() {
                    calculateAmount(this.dataset.index);
                });
            });
            
            // 使用事件委托处理按钮点击
            document.addEventListener('click', function(event) {
                // 处理删除服务按钮
                if (event.target.classList.contains('btn-delete-service')) {
                    const rowToDelete = event.target.closest('tr');
                    
                    // Case 1: Deleting the category head row (which is also the first data row)
                    if (rowToDelete.classList.contains('service-category-row')) {
                        const nextRow = rowToDelete.nextElementSibling;
                        const categoryId = rowToDelete.id;

                        // Check if there are more items (if next row is a service-row)
                        if (nextRow && nextRow.classList.contains('service-row')) {
                            // Yes, promote the next row to be the new category head
                        const categoryCell = rowToDelete.querySelector('.category-name-cell');
                            if (categoryCell) {
                                rowToDelete.removeAttribute('id'); // Avoid duplicate IDs
                                nextRow.id = categoryId;
                            nextRow.classList.add('service-category-row');
                            nextRow.classList.remove('service-row');
                                nextRow.prepend(categoryCell); // Move the category cell
                            }
                            rowToDelete.remove(); // Remove the old, now empty, head row
                            setTimeout(() => updateCategoryRowspan(categoryId), 0);
                        } else {
                            // No, this is the last item. Delete the whole category block.
                            rowToDelete.remove();
                            // also remove the "add button" row that follows it.
                            if (nextRow && nextRow.querySelector('.btn-add-service, .btn-add-service-dynamic')) {
                                nextRow.remove();
                            }
                        }
                    } 
                    // Case 2: Deleting a "child" service row
                    else if (rowToDelete.classList.contains('service-row')) {
                        // Find its category header to update rowspan later
                        let categoryRow = null;
                        let prevSibling = rowToDelete.previousElementSibling;
                        while(prevSibling) {
                            if (prevSibling.classList.contains('service-category-row')) {
                                categoryRow = prevSibling;
                                break;
                            }
                            prevSibling = prevSibling.previousElementSibling;
                        }

                        const categoryId = categoryRow ? categoryRow.id : null;
                    rowToDelete.remove();
                        
                        if (categoryId) {
                            setTimeout(() => updateCategoryRowspan(categoryId), 0);
                        }
                    }

                    calculateTotal(); // Recalculate total in all deletion cases
                    return; // We've handled the delete, so we can exit.
                }

                // 处理添加服务按钮 - 基本类别
                if (event.target === document.getElementById('addServiceBtn') || 
                    event.target.closest('#addServiceBtn')) {
                    addService();
                return;
            }

                // 处理添加服务类别按钮
                if (event.target === document.getElementById('addCategoryBtn') || 
                    event.target.closest('#addCategoryBtn')) {
                    addServiceCategory();
                return;
            }

                // 处理动态添加的类别服务按钮
                if (event.target.matches('.btn-add-service-dynamic')) {
                    const categoryId = event.target.dataset.categoryId;
                    if (categoryId) {
                        addServiceToCategory(categoryId);
                    }
                    return;
                }
            });
            
            // 预览按钮事件
            document.getElementById('previewBtn').addEventListener('click', showPreview);
            
            // 导出按钮事件
            document.getElementById('exportBtn').addEventListener('click', exportToExcel);
            
            // 关闭模态框按钮事件
            document.querySelector('.modal-close-btn').addEventListener('click', function() {
                document.getElementById('previewModal').style.display = 'none';
            });
            
            // 点击模态框背景关闭模态框
            document.getElementById('previewModal').addEventListener('click', function(event) {
                if (event.target === this) {
                    this.style.display = 'none';
                }
            });
            
            // 初始计算总计
            calculateTotal();
            // 初始更新基础服务的rowspan
            updateCategoryRowspan('category-basic');
            
            // 检查提交按钮状态
            checkSubmitButtonStatus();
        });
        
        // 显示预览
        function showPreview() {
            const modalBody = document.querySelector('#previewModal .modal-body');
            let tableHTML = `<table class="preview-table">
                <thead>
                    <tr>
                        <th style="width: 10%;">服务<br/>类别</th>
                        <th style="width: 15%;">服务名称</th>
                        <th style="width: 15%;">项目</th>
                        <th style="width: 8%;">单位</th>
                        <th style="width: 8%;">单价</th>
                        <th style="width: 8%;">数量</th>
                        <th style="width: 8%;">租用<br/>期限</th>
                        <th style="width: 8%;">合计</th>
                        <th style="width: 15%;">备注</th>
                    </tr>
                </thead>
                <tbody>`;
            
            // 获取所有服务类别
            const categoryRows = document.querySelectorAll('.service-category-row');
            
            // 遍历每个服务类别
            categoryRows.forEach(categoryRow => {
                // 获取当前类别名称
                const categoryInput = categoryRow.querySelector('.category-input');
                const categoryName = categoryInput ? categoryInput.value : '基础服务';
                
                // 获取当前类别的ID
                const categoryId = categoryRow.id;
                
                // 获取该类别下的所有服务行
                let currentRow = categoryRow;
                
                // 处理类别行中的第一个服务
                const serviceName = currentRow.querySelector('[name^="service_name_"]')?.value || '';
                const item = currentRow.querySelector('[name^="item_"]')?.value || '';
                const unit = currentRow.querySelector('[name^="unit_"]')?.value || '';
                const price = currentRow.querySelector('[name^="price_"]')?.value || '0.00';
                const quantity = currentRow.querySelector('[name^="quantity_"]')?.value || '0';
                const leaseTerm = currentRow.querySelector('[name^="lease_term_"]')?.value || '';
                const total = currentRow.querySelector('[name^="total_"]')?.value || '0.00';
                const notes = currentRow.querySelector('[name^="notes_"]')?.value || '';
                
                // 添加第一个服务行到预览
                tableHTML += `<tr>
                    <td>${categoryName}</td>
                    <td>${serviceName}</td>
                    <td>${item}</td>
                    <td>${unit}</td>
                    <td style="text-align: right;">${price}</td>
                    <td style="text-align: right;">${quantity}</td>
                    <td>${leaseTerm}</td>
                    <td style="text-align: right;">${total}</td>
                    <td>${notes}</td>
                </tr>`;
                
                // 获取该类别下的所有其他服务行
                currentRow = currentRow.nextElementSibling;
                while (currentRow && !currentRow.classList.contains('service-category-row')) {
                    // 跳过添加按钮行
                    if (currentRow.querySelector('.btn-add-service, .btn-add-service-dynamic')) {
                        currentRow = currentRow.nextElementSibling;
                        continue;
                    }

                    // 获取服务行数据
                    const serviceName = currentRow.querySelector('[name^="service_name_"]')?.value || '';
                    const item = currentRow.querySelector('[name^="item_"]')?.value || '';
                    const unit = currentRow.querySelector('[name^="unit_"]')?.value || '';
                    const price = currentRow.querySelector('[name^="price_"]')?.value || '0.00';
                    const quantity = currentRow.querySelector('[name^="quantity_"]')?.value || '0';
                    const leaseTerm = currentRow.querySelector('[name^="lease_term_"]')?.value || '';
                    const total = currentRow.querySelector('[name^="total_"]')?.value || '0.00';
                    const notes = currentRow.querySelector('[name^="notes_"]')?.value || '';
                    
                    // 添加服务行到预览
                    tableHTML += `<tr>
                        <td>${categoryName}</td>
                        <td>${serviceName}</td>
                        <td>${item}</td>
                        <td>${unit}</td>
                        <td style="text-align: right;">${price}</td>
                        <td style="text-align: right;">${quantity}</td>
                        <td>${leaseTerm}</td>
                        <td style="text-align: right;">${total}</td>
                        <td>${notes}</td>
                    </tr>`;
                    
                    currentRow = currentRow.nextElementSibling;
                }
            });
            
            // 添加总计行
            const overallTotal = document.getElementById('overallTotal').value || '0.00';
            tableHTML += `<tr style="background-color: #f0f5ff; font-weight: bold;">
                <td colspan="7" style="text-align: right;">合计：</td>
                <td style="text-align: right;">${overallTotal}</td>
                <td></td>
            </tr>`;
            
            tableHTML += `</tbody></table>`;
            modalBody.innerHTML = tableHTML;
            document.getElementById('previewModal').style.display = 'flex';
        }
        
        // 导出到Excel
        function exportToExcel() {
            // 创建数据数组
            const data = [];
            // 添加表头
            data.push([
                '服务类别', '服务名称', '项目', '单位', '单价', '数量', 
                '租用期限', '合计', '备注'
            ]);
            
            // 获取所有服务类别
            const categoryRows = document.querySelectorAll('.service-category-row');
            
            // 遍历每个服务类别
            categoryRows.forEach(categoryRow => {
                // 获取当前类别名称
                const categoryInput = categoryRow.querySelector('.category-input');
                const categoryName = categoryInput ? categoryInput.value : '基础服务';

                // 获取当前类别的ID
                const categoryId = categoryRow.id;
                
                // 获取该类别下的所有服务行
                let currentRow = categoryRow;
                
                // 处理类别行中的第一个服务
                const serviceName = currentRow.querySelector('[name^="service_name_"]')?.value || '';
                const item = currentRow.querySelector('[name^="item_"]')?.value || '';
                const unit = currentRow.querySelector('[name^="unit_"]')?.value || '';
                const price = parseFloat(currentRow.querySelector('[name^="price_"]')?.value || '0');
                const quantity = parseFloat(currentRow.querySelector('[name^="quantity_"]')?.value || '0');
                const leaseTerm = currentRow.querySelector('[name^="lease_term_"]')?.value || '';
                const total = parseFloat(currentRow.querySelector('[name^="total_"]')?.value || '0');
                const notes = currentRow.querySelector('[name^="notes_"]')?.value || '';
                
                // 添加第一个服务行到数据
                data.push([
                    categoryName, serviceName, item, unit, price, quantity, 
                    leaseTerm, total, notes
                ]);
                
                // 获取该类别下的所有其他服务行
                currentRow = currentRow.nextElementSibling;
                while (currentRow && !currentRow.classList.contains('service-category-row')) {
                    // 跳过添加按钮行
                    if (currentRow.querySelector('.btn-add-service, .btn-add-service-dynamic')) {
                        currentRow = currentRow.nextElementSibling;
                        continue;
                    }
                    
                    // 获取服务行数据
                    const serviceName = currentRow.querySelector('[name^="service_name_"]')?.value || '';
                    const item = currentRow.querySelector('[name^="item_"]')?.value || '';
                    const unit = currentRow.querySelector('[name^="unit_"]')?.value || '';
                    const price = parseFloat(currentRow.querySelector('[name^="price_"]')?.value || '0');
                    const quantity = parseFloat(currentRow.querySelector('[name^="quantity_"]')?.value || '0');
                    const leaseTerm = currentRow.querySelector('[name^="lease_term_"]')?.value || '';
                    const total = parseFloat(currentRow.querySelector('[name^="total_"]')?.value || '0');
                    const notes = currentRow.querySelector('[name^="notes_"]')?.value || '';
                    
                    // 添加服务行到数据
                    data.push([
                        categoryName, serviceName, item, unit, price, quantity, 
                        leaseTerm, total, notes
                    ]);
                    
                    currentRow = currentRow.nextElementSibling;
                }
            });
            
            // 添加空白行和总计行
            data.push([]);
            const overallTotal = parseFloat(document.getElementById('overallTotal').value || '0');
            data.push(['总计', '', '', '', '', '', '', overallTotal, '']);
            
            // 创建工作表
            const worksheet = XLSX.utils.aoa_to_sheet(data);
            
            // 设置列宽
            worksheet['!cols'] = [
                { wch: 15 }, { wch: 15 }, { wch: 20 }, { wch: 10 }, 
                { wch: 10 }, { wch: 10 }, { wch: 10 }, { wch: 12 }, { wch: 20 }
            ];
            
            // 设置数字格式
            for (let i = 1; i < data.length; i++) {
                const priceCell = 'E' + (i + 1);
                const quantityCell = 'F' + (i + 1);
                const totalCell = 'H' + (i + 1);
                
                if (worksheet[priceCell] && worksheet[priceCell].t === 'n') {
                    worksheet[priceCell].z = '#,##0.00';
                }
                
                if (worksheet[quantityCell] && worksheet[quantityCell].t === 'n') {
                    worksheet[quantityCell].z = '#,##0';
                }
                
                if (worksheet[totalCell] && worksheet[totalCell].t === 'n') {
                    worksheet[totalCell].z = '#,##0.00';
                }
            }
            
            // 创建工作簿并添加工作表
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '市级政务云租用明细');
            
            // 下载Excel文件
            XLSX.writeFile(workbook, '市级政务云租用明细.xlsx');
        }

        // 完全重写addServiceCategory函数，确保新添加的服务类别直接添加到现有表格中
        function addServiceCategory() {
            // 获取表格体
            const cloudServiceBody = document.getElementById('cloudServiceBody');
            
            // 创建新的服务类别行
            const newRowId = Date.now(); // 使用时间戳作为唯一ID
            const categoryRow = document.createElement('tr');
            categoryRow.className = 'service-category-row';
            categoryRow.id = `category-${newRowId}`;
            
            // 设置服务类别行内容
            categoryRow.innerHTML = `
                <td rowspan="2" class="category-name-cell">
                    <input type="text" class="category-input" value="新服务类别" placeholder="服务类别名称">
                </td>
                <td><input type="text" class="cloud-input" name="service_name_${newRowId}" value="新服务"></td>
                <td><input type="text" class="cloud-input" name="item_${newRowId}" value=""></td>
                <td><input type="text" class="cloud-input" name="unit_${newRowId}" value="元/月"></td>
                <td><input type="number" class="cloud-input text-right" name="price_${newRowId}" data-index="${newRowId}"></td>
                <td><input type="number" class="cloud-input" name="quantity_${newRowId}" data-index="${newRowId}"></td>
                <td><input type="text" class="cloud-input" name="lease_term_${newRowId}"></td>
                <td><input type="text" class="cloud-input text-right" name="total_${newRowId}" readonly></td>
                <td><input type="text" class="cloud-input" name="notes_${newRowId}"></td>
                <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
            `;
            
            // 创建添加按钮行，与原来的样式保持一致
            const buttonRow = document.createElement('tr');
            buttonRow.innerHTML = `
                <td colspan="9" style="text-align: center;">
                    <button type="button" class="btn-add-service" id="addServiceBtn-${newRowId}">
                        <i class="fas fa-plus-circle"></i> 添加服务名称
                    </button>
                </td>
            `;

            // 添加到表格中
            cloudServiceBody.appendChild(categoryRow);
            cloudServiceBody.appendChild(buttonRow);
            
            // 为价格和数量输入框添加事件监听器
            const priceInput = categoryRow.querySelector(`input[name="price_${newRowId}"]`);
            const quantityInput = categoryRow.querySelector(`input[name="quantity_${newRowId}"]`);
            
            if (priceInput) {
                priceInput.addEventListener('input', function() {
                    calculateAmount(newRowId);
                });
            }
            
            if (quantityInput) {
                quantityInput.addEventListener('input', function() {
                    calculateAmount(newRowId);
                });
            }
            
            // 为添加服务按钮添加事件监听器
            const addServiceBtn = document.getElementById(`addServiceBtn-${newRowId}`);
            if (addServiceBtn) {
                addServiceBtn.classList.add('btn-add-service-dynamic');
                addServiceBtn.dataset.categoryId = categoryRow.id;
            }
        }

        // 修改addServiceToCategory函数以配合新的addServiceCategory函数
        function addServiceToCategory(categoryId) {
            // 从 categoryId (e.g., "category-123456") 中提取数字ID
            const categoryTimestamp = categoryId.split('-')[1];
            if (!categoryTimestamp) return;

            // 找到对应类别的添加按钮行
            let buttonRow = document.getElementById(`addServiceBtn-${categoryTimestamp}`).closest('tr');
            
            if (!buttonRow) return;
            
            // 创建新服务行
            const newRowId = `${categoryTimestamp}-${Date.now()}`; // 使用时间戳作为唯一ID
            const newServiceRow = document.createElement('tr');
            newServiceRow.className = 'service-row';
            
            // 设置新行内容
            newServiceRow.innerHTML = `
                <td><input type="text" class="cloud-input" name="service_name_${newRowId}"></td>
                <td><input type="text" class="cloud-input" name="item_${newRowId}"></td>
                <td><input type="text" class="cloud-input" name="unit_${newRowId}" value="元/月"></td>
                <td><input type="number" class="cloud-input text-right" name="price_${newRowId}" data-index="${newRowId}"></td>
                <td><input type="number" class="cloud-input" name="quantity_${newRowId}" data-index="${newRowId}"></td>
                <td><input type="text" class="cloud-input" name="lease_term_${newRowId}"></td>
                <td><input type="text" class="cloud-input text-right" name="total_${newRowId}" readonly></td>
                <td><input type="text" class="cloud-input" name="notes_${newRowId}"></td>
                <td class="operation-cell"><button type="button" class="btn-delete-service" title="删除">-</button></td>
            `;
            
            // 在添加按钮行之前插入新行
            buttonRow.parentNode.insertBefore(newServiceRow, buttonRow);
            
            // 更新类别单元格的rowspan
            updateCategoryRowspan(categoryId);
            
            // 为新行的价格和数量输入框添加事件监听器
            const priceInput = newServiceRow.querySelector(`input[name="price_${newRowId}"]`);
            const quantityInput = newServiceRow.querySelector(`input[name="quantity_${newRowId}"]`);
            
            if (priceInput) {
                priceInput.addEventListener('input', function() {
                    calculateAmount(newRowId);
                });
            }
            
            if (quantityInput) {
                quantityInput.addEventListener('input', function() {
                    calculateAmount(newRowId);
                });
            }
        }

        // 检查提交按钮状态
        function checkSubmitButtonStatus() {
            // 从localStorage获取所有页面的完成状态
            const basicInfoCompleted = localStorage.getItem('basicInfoCompleted') === 'true';
            const budgetCompleted = localStorage.getItem('budgetCompleted') === 'true';
            const productCompleted = localStorage.getItem('productCompleted') === 'true';
            const softwareCompleted = localStorage.getItem('softwareCompleted') === 'true';
            const implementationCompleted = localStorage.getItem('implementationCompleted') === 'true';
            
            // 当前页面（云服务）自动标记为已完成
            localStorage.setItem('cloudCompleted', 'true');
            const cloudCompleted = true;
            
            // 只有当所有页面都完成时，才启用提交按钮
            const allCompleted = basicInfoCompleted && budgetCompleted && productCompleted && 
                                softwareCompleted && implementationCompleted && cloudCompleted;
            
            document.getElementById('submitBtn').disabled = !allCompleted;
            
            if (allCompleted) {
                document.getElementById('submitBtn').style.opacity = '1';
            } else {
                document.getElementById('submitBtn').style.opacity = '0.6';
            }
        }
        
        // 保存按钮事件
        document.getElementById('saveBtn').addEventListener('click', function() {
            // 标记当前页面已完成
            localStorage.setItem('cloudCompleted', 'true');
            
            // 检查提交按钮状态
            checkSubmitButtonStatus();
            
            showCustomAlert('政务云租用明细已保存');
        });
        
        // 上一步按钮事件
        document.getElementById('prevBtn').addEventListener('click', function() {
            window.location.href = 'implementation-service.html';
        });
        
        // 提交按钮事件
        document.getElementById('submitBtn').addEventListener('click', function() {
            if (!this.disabled) {
                showCustomConfirm('确认提交项目申报审核吗？提交后将不能再修改。', function(confirmed) {
                    if (confirmed) {
                        showCustomAlert('项目申报已提交审核，请等待审核结果。');
                        setTimeout(function() {
                        window.location.href = '../project-submit.html';
                        }, 1500);
                    }
                });
            }
        });
    </script>
</body>
</html> 